package com.qqtech.qquan.im.service;

import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import jersey.repackaged.com.google.common.collect.Lists;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.glassfish.jersey.client.JerseyWebTarget;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.im.dao.ImGroupDao;
import com.qqtech.qquan.im.dao.ImUserDao;
import com.qqtech.qquan.im.enums.HTTPMethod;
import com.qqtech.qquan.im.helper.ImSettings;
import com.qqtech.qquan.im.jersey.Credential;
import com.qqtech.qquan.im.jersey.EndPoints;
import com.qqtech.qquan.im.jersey.JerseyUtils;
import com.qqtech.qquan.im.model.ImGroup;
import com.qqtech.qquan.im.model.ImMessage;
import com.qqtech.qquan.im.model.ImMessageBody;
import com.qqtech.qquan.im.model.ImMessageVo;
import com.qqtech.qquan.im.model.ImUser;

@Service
public class ImMessageServiceImpl extends BaseServiceImpl<ImMessage> implements ImMessageService {
	public static final Logger LOGGER = LoggerFactory.getLogger(ImMessageServiceImpl.class);
	private static final JsonNodeFactory factory = new JsonNodeFactory(false);
	
	@Resource
	private ImUserDao imUserDao;
	@Resource
	private ImGroupDao imGroupDao;
	@Resource
    private ImSettings imSettings;
	@Resource
	private Credential credential;
	
	@Override
	protected BaseDao<ImMessage> getBaseDao() {
		return null;
	}

	
/* {
    "type": "chatmessage",
    "from": "zw123", //发送人username
    "msg_id": "5I02W-16-8278a", //消息ID
    "chat_type": "chat", //用来判断单聊还是群聊。chat: 单聊；groupchat: 群聊
    "payload": {
        "bodies": [{ "msg": "hhhhhh", //消息内容
            "type": "txt" //消息类型。txt: 文本消息；img: 图片；loc: 位置；audio: 语音
            "length": 3, //语音时长，单位为秒，这个属性只有语音消息有
            "url": "", //图片语音等文件的网络URL，图片和语音消息有这个属性
            "filename": "22.png", //文件名字，图片和语音消息有这个属性
            "secret": "pCY80PdfEeO4Jh9URCOfMQWU9QYsJytynu4n-yhtvAhmt1g9", //获取文件的secret，图片和语音消息有这个属性
            "lat": 39.983805, //发送的位置的纬度，只有位置消息有这个属性
            "lng": 116.307417, //位置经度，只有位置消息有这个属性
            "addr": "北京市海淀区北四环西路66号" //位置消息详细地址，只有位置消息有这个属性
          }]
        "ext": { //自定义扩展属性
        	"key1": "value1",   //你设置的key和value的值
		   ...
         },
    },
    "timestamp": 1403099033211, //消息发送时间
    "to": "1402541206787" //接收人的username或者接收group的ID
}
*/
	@Override
	public List<ImMessageVo> get2UserMessages(Integer userId1,Integer userId2,Timestamp startTime) {
		List<ImMessageVo> messageList = Lists.newArrayList();
		ImUser user1 = imUserDao.getByUserId(userId1);
		ImUser user2 = imUserDao.getByUserId(userId2);
		if(user1!=null && user2!=null){
			String imId1 = user1.getImId();
			String imId2 = user2.getImId();
			ObjectNode queryStrNode1 = factory.objectNode();
			//String sql0 = "select * where timestamp > " + startTime.getTime();
			String sql = "select * where timestamp > " + startTime.getTime() +" and ((from = '"+imId1+"' and to ='"+imId2+"') or (from = '"+imId2+"' and to ='"+imId1+"'))" ;
			queryStrNode1.put("ql", sql);
			queryStrNode1.put("limit", "1000");        
	        ObjectNode messages = getChatMessagesByApi(queryStrNode1);
	        Iterable<JsonNode> JsonNodeList =messages.get("entities");
	        ImMessageVo message = null;
	        ImMessageBody messageBody = null;
	        String bodyType = null;//消息类型：txt: 文本消息；img: 图片；loc: 位置；audio: 语音
	        for(JsonNode oneMsg :JsonNodeList){
	        	message = new ImMessageVo();
	        	messageBody = new ImMessageBody();
	        	message.setMessageId(oneMsg.get("msg_id").asText());
	        	message.setFrom(oneMsg.get("from").asText());
	        	message.setTo(oneMsg.get("to").asText());
	        	message.setChatType(oneMsg.get("chat_type").asText());
	        	message.setTimestamp(oneMsg.get("timestamp").asLong());//消息发送时间
	        	bodyType = oneMsg.get("payload").path("bodies").get(0).path("type").asText();//消息类型
	        	messageBody = new ImMessageBody();
	        	if(bodyType.equalsIgnoreCase("txt")){
	        		messageBody.setType(0);//0.Text(文本)
	        		messageBody.setText(oneMsg.get("payload").path("bodies").get(0).path("msg").asText());
	        	}else if(bodyType.equalsIgnoreCase("img")){
	        		messageBody.setType(1);//1.Image(图片)
	        		messageBody.setRemotePath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setLocalPath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setThumbnailRemotePath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setThumbnailLocalPath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		
	        		messageBody.setFileLength(oneMsg.get("payload").path("bodies").get(0).path("file_length").asInt());
	        	}else if(bodyType.equalsIgnoreCase("audio")){
	        		messageBody.setType(3);//3.Voice(语音)
	        		messageBody.setRemotePath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setLocalPath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setThumbnailRemotePath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setThumbnailLocalPath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		
	        		messageBody.setFileLength(oneMsg.get("payload").path("bodies").get(0).path("file_length").asInt());
	        		messageBody.setDuration(oneMsg.get("payload").path("bodies").get(0).path("length").asInt());//语音长度(秒)
	        	}
	        	message.setBody(messageBody);
	        	messageList.add(message);
	        }
		}
		
        return messageList;
	}
	
	private ObjectNode getChatMessagesByApi(ObjectNode queryStrNode) {
		ObjectNode objectNode = factory.objectNode();
		try {
			String APPKEY = imSettings.getAppKey();
			JerseyWebTarget webTarget = EndPoints.CHATMESSAGES_TARGET.resolveTemplate("org_name", APPKEY.split("#")[0])
					.resolveTemplate("app_name", APPKEY.split("#")[1]);
			if (null != queryStrNode && null != queryStrNode.get("ql") && !StringUtils.isEmpty(queryStrNode.get("ql").asText())) {
				webTarget = webTarget.queryParam("ql", queryStrNode.get("ql").asText());
			}
			if (null != queryStrNode && null != queryStrNode.get("limit") &&!StringUtils.isEmpty(queryStrNode.get("limit").asText())) {
				webTarget = webTarget.queryParam("limit", queryStrNode.get("limit").asText());
			}
			if (null != queryStrNode && null != queryStrNode.get("cursor") &&!StringUtils.isEmpty(queryStrNode.get("cursor").asText())) {
				webTarget = webTarget.queryParam("cursor", queryStrNode.get("cursor").asText());
			}
			objectNode = JerseyUtils.sendRequest(webTarget, null, credential, HTTPMethod.METHOD_GET, null);
			int statusCode =objectNode.get("statusCode").asInt();//200成功，401验证失败
		    if(statusCode==HttpStatus.SC_UNAUTHORIZED){//401验证失败
		    	credential.getNewToken();//重新获取一个token
		    	objectNode = JerseyUtils.sendRequest(webTarget, null, credential, HTTPMethod.METHOD_GET, null);
		    }
		    
		} catch (Exception e) {
			e.printStackTrace();
		}
		return objectNode;
	}
	
	@Override
	public List<ImMessageVo> getGroupMessages(Integer groupId,Timestamp startTime) {
		List<ImMessageVo> messageList = Lists.newArrayList();
		ImGroup group = imGroupDao.getByGroupId(groupId);
		if(group!=null){
			String imGroupId = group.getImGroupId();
			ObjectNode queryStrNode1 = factory.objectNode();
			//String sql0 = "select * where timestamp > " + startTime.getTime();
			String sql = "select * where timestamp > " + startTime.getTime() +" and to ='"+imGroupId+"'" ;
			queryStrNode1.put("ql", sql);
			queryStrNode1.put("limit", "2000");        
	        ObjectNode messages = getChatMessagesByApi(queryStrNode1);
	        Iterable<JsonNode> JsonNodeList =messages.get("entities");
	        ImMessageVo message = null;
	        ImMessageBody messageBody = null;
	        String bodyType = null;//消息类型：txt: 文本消息；img: 图片；loc: 位置；audio: 语音
	        for(JsonNode oneMsg :JsonNodeList){
	        	message = new ImMessageVo();
	        	messageBody = new ImMessageBody();
	        	message.setMessageId(oneMsg.get("msg_id").asText());
	        	message.setFrom(oneMsg.get("from").asText());
	        	message.setTo(oneMsg.get("to").asText());
	        	message.setChatType(oneMsg.get("chat_type").asText());
	        	message.setTimestamp(oneMsg.get("timestamp").asLong());//消息发送时间
	        	bodyType = oneMsg.get("payload").path("bodies").get(0).path("type").asText();//消息类型
	        	messageBody = new ImMessageBody();
	        	if(bodyType.equalsIgnoreCase("txt")){
	        		messageBody.setType(0);//0.Text(文本)
	        		messageBody.setText(oneMsg.get("payload").path("bodies").get(0).path("msg").asText());
	        	}else if(bodyType.equalsIgnoreCase("img")){
	        		messageBody.setType(1);//1.Image(图片)
	        		messageBody.setRemotePath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setLocalPath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setThumbnailRemotePath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setThumbnailLocalPath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		
	        		messageBody.setFileLength(oneMsg.get("payload").path("bodies").get(0).path("file_length").asInt());
	        	}else if(bodyType.equalsIgnoreCase("audio")){
	        		messageBody.setType(3);//3.Voice(语音)
	        		messageBody.setRemotePath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setLocalPath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setThumbnailRemotePath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		messageBody.setThumbnailLocalPath(oneMsg.get("payload").path("bodies").get(0).path("url").asText());
	        		
	        		messageBody.setFileLength(oneMsg.get("payload").path("bodies").get(0).path("file_length").asInt());
	        		messageBody.setDuration(oneMsg.get("payload").path("bodies").get(0).path("length").asInt());//语音长度(秒)
	        	}
	        	message.setBody(messageBody);
	        	messageList.add(message);
	        }
		}
		
        return messageList;
	}
	
}